<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="mrNumber">
              <el-input v-model="queryParams.mrNumber" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="医代名称" prop="mrName">
              <el-input v-model="queryParams.mrName" placeholder="请输入医药代表名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="mrPhonenumber">
              <el-input v-model="queryParams.mrPhonenumber" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:agentMr:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:agentMr:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:agentMr:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="agentMrList" @selection-change="handleSelectionChange">
        <el-table-column label="编号" align="center" prop="mrNumber" />
        <el-table-column label="所属国代" align="center" prop="agentGdName" />
        <el-table-column label="所属省代" align="center" prop="agentSdName" />
        <el-table-column label="医药代表名称" align="center" prop="mrName" />
        <el-table-column label="联系电话" align="center" prop="mrPhonenumber" />
        <el-table-column label="分佣比率" align="center" prop="commissionRate">
          <template #default="scope">
            <el-tag type="warning" effect="plain">{{ scope.row.commissionRate }}元</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="amountTotal" />
        <el-table-column label="当前金额" align="center" prop="amountCurrent" />
        <el-table-column label="已提现金额" align="center" prop="amountWithdraw" />
        <el-table-column label="冻结金额" align="center" prop="amountFreeze" />
        <el-table-column label="剩余次数" align="center" prop="balanceCurrent">
          <template #default="scope">
            {{ parseInt(scope.row.balanceCurrent) }}
          </template>
        </el-table-column>
        <el-table-column label="已使用次数" align="center" prop="balanceUsed">
          <template #default="scope">
            {{ parseInt(scope.row.balanceUsed) }}
          </template>
        </el-table-column>
        <el-table-column label="登陆账号" align="center" prop="username" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="busi_agent_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['business:agentMr:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.userId !== 1" content="重置密码" placement="top">
              <el-button v-hasPermi="['business:agentMr:edit']" link type="primary" icon="Key" @click="handleResetPwd(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="充值次数" placement="top">
              <el-button v-hasPermi="['business:agentMr:recharge']" link type="success" icon="Money" @click="handleRecharge(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改医药代表管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="680px" append-to-body>
      <el-form ref="agentMrFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item v-if="form.id" label="编号" prop="mrNumber">
          <el-input v-model="form.mrNumber" placeholder="请输入编号" disabled />
        </el-form-item>
        <el-form-item v-if="form.id" label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" disabled />
        </el-form-item>
        <el-form-item label="医药代表名称" prop="mrName">
          <el-input v-model="form.mrName" placeholder="请输入医药代表名称" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="登录密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入登录密码" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="联系电话" prop="mrPhonenumber">
          <el-input v-model="form.mrPhonenumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="省/市/区" prop="province">
          <el-cascader v-model="form.regionInfo" :options="regionInfoOptions" :props="props" @change="handleChange" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="身份证" prop="identityCard">
          <image-upload v-model="form.identityCard" :limit="1" />
        </el-form-item>
        <el-form-item label="分佣比率" prop="commissionRate">
          <el-input-number v-model="form.commissionRate" :min="1.0" :max="1.0" :precision="2" :step="0.01" />
        </el-form-item>
        <el-form-item label="开关-接收消息" prop="switchMsg">
          <el-radio-group v-model="form.switchMsg">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in busi_agent_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AgentMr" lang="ts">
import { listAgentMr, getAgentMr, addAgentMr, updateAgentMr, resetUserPwd, recharge } from '@/api/business/agentMr';
import { AgentMrVO, AgentMrQuery, AgentMrForm } from '@/api/business/agentMr/types';
import CnRegionInfo from '@/assets/data/cn_region_info.json';
import { to } from 'await-to-js';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { busi_agent_status, sys_normal_disable } = toRefs<any>(proxy?.useDict('busi_agent_status', 'sys_normal_disable'));

const agentMrList = ref<AgentMrVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const agentMrFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const props = {
  expandTrigger: 'hover' as const
};
const regionInfoOptions = CnRegionInfo;

const initFormData: AgentMrForm = {
  id: undefined,
  agentGdId: undefined,
  agentSdId: undefined,
  sysUserId: undefined,
  mrNumber: undefined,
  mrName: undefined,
  mrPhonenumber: undefined,
  country: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  address: undefined,
  identityCard: undefined,
  commissionRate: 1.0,
  amountTotal: undefined,
  amountCurrent: undefined,
  amountWithdraw: undefined,
  amountFreeze: undefined,
  switchMsg: 0,
  status: 0,
  otherVal: undefined,
  remark: undefined
};
const data = reactive<PageData<AgentMrForm, AgentMrQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    agentGdId: undefined,
    agentSdId: undefined,
    sysUserId: undefined,
    mrNumber: undefined,
    mrName: undefined,
    mrPhonenumber: undefined,
    country: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    address: undefined,
    commissionRate: undefined,
    amountTotal: undefined,
    amountCurrent: undefined,
    amountWithdraw: undefined,
    amountFreeze: undefined,
    switchMsg: undefined,
    status: undefined,
    otherVal: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    mrName: [{ required: true, message: '医药代表名称不能为空', trigger: 'blur' }],
    username: [
      { required: true, message: '登录账号不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '登录账号长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '登录密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '登录密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ],
    mrPhonenumber: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    identityCard: [{ required: true, message: '身份证不能为空', trigger: 'blur' }],
    commissionRate: [{ required: true, message: '分佣比率不能为空', trigger: 'blur' }],
    switchMsg: [{ required: true, message: '开关-接收消息不能为空', trigger: 'change' }]
    // status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询医药代表管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAgentMr(queryParams.value);
  agentMrList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  agentMrFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AgentMrVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加医药代表';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AgentMrVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAgentMr(_id);
  Object.assign(form.value, res.data);
  let regionInfo = [];
  if (form.value.province !== undefined) {
    regionInfo.push(form.value.province);
  }
  if (form.value.city !== undefined) {
    regionInfo.push(form.value.city);
  }
  if (form.value.district !== undefined) {
    regionInfo.push(form.value.district);
  }
  form.value.regionInfo = regionInfo;
  dialog.visible = true;
  dialog.title = '修改医药代表';
};

/** 提交按钮 */
const submitForm = () => {
  agentMrFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAgentMr(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAgentMr(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
// const handleDelete = async (row?: AgentMrVO) => {
//   const _ids = row?.id || ids.value;
//   await proxy?.$modal.confirm('是否确认删除医药代表管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
//   await delAgentMr(_ids);
//   proxy?.$modal.msgSuccess('删除成功');
//   await getList();
// };

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/agentMr/export',
    {
      ...queryParams.value
    },
    `agentMr_${new Date().getTime()}.xlsx`
  );
};

const handleChange = (value: string) => {
  form.value.province = value[0];
  form.value.city = value[1];
  if (value.length === 3) {
    form.value.district = value[2];
  } else {
    form.value.district = '';
  }
};

/** 重置密码按钮操作 */
const handleResetPwd = async (row: AgentMrVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入医药代表"' + row.mrName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
    })
  );
  if (!err) {
    await resetUserPwd(row.sysUserId, res.value);
    proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value);
  }
};

const handleRecharge = async (row: AgentMrVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入医药代表"' + row.mrName + '"的充值次数', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^\d+$/,
      inputErrorMessage: '充值额度必须是一个正整数'
    })
  );
  if (!err) {
    await recharge(row.id, res.value);
    proxy?.$modal.msgSuccess('充值成功' + res.value);
    await getList();
  }
};

onMounted(() => {
  getList();
});
</script>
